import {Fragment, PureComponent} from 'react';
import {
  Card,
  Popconfirm,
  Form,
  Row,
  Col,
  Input,
  Button,
  message,
  Select,
  Radio,
  Modal,
  Divider,
  InputNumber,
  Switch,
  Badge
} from 'antd';
import React from 'react';
import Icon from '@ant-design/icons';
import {connect} from "umi";
import {formatMessage} from "@@/plugin-locale/localeExports";
import ProTable from '@ant-design/pro-table';
import styles from '../common.less';
import {hasPermission, nopermission} from "@/hasPermission";
import {add, update} from "@/pages/RouteList/service";

const { Option } = Select;

class RouteList extends PureComponent{

  state = {
    formValues: {},
    updateFormValues: {},
    currentPage: 1,
    pageSize: 10,
    modalVisible: false,
    routes: [],
    iconVal: null
  }

  columns = [
    {
      title: formatMessage({ id: 'app.routeList.name' }),
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.routeList.parentId' }),
      dataIndex: 'parentName',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.routeList.icon' }),
      dataIndex: 'icon',
      align: 'center',
      render: (val) =>
        <span className='.anticon.font'>
          <span className={`iconfont ${val}`}></span>
        </span>
    },
    {
      title: formatMessage({ id: 'app.routeList.path' }),
      dataIndex: 'path',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.routeList.component' }),
      dataIndex: 'component',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.routeList.access' }),
      dataIndex: 'access',
      align: 'center',
      render: (val) => <span>{val == 'canAdmin' ? '管理员' : '普通用户'}</span>
    },
    {
      title: formatMessage({ id: 'app.routeList.hideInMenu' }),
      dataIndex: 'hideInMenu',
      align: 'center',
      render: (val) => <Badge status={!val ? 'success' : 'default'} text={!val ? '显示' : '隐藏'}/>
    },
    {
      title: formatMessage({ id: 'app.routeList.seq' }),
      dataIndex: 'seq',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '100px',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>
            <Icon type='edit' />
            {formatMessage({ id: 'app.common.edit' })}
          </a>
          <Divider type="vertical"/>
          <Popconfirm
          title={formatMessage({ id: 'app.common.confirm-delete' })}
          onConfirm={() => this.deleteRecord(record.id)}
          >
            <a>
              <Icon type='delete' />
              {formatMessage({ id: 'app.common.delete' })}
            </a>
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'routeList/fetch'
    });
    this.formRef = React.createRef();
    this.formRef2 = React.createRef();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    if (sorter.field && sorter.order) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({ currentPage: pagination.current, pageSize: pagination.pageSize });
    dispatch({
      type: 'routeList/fetch',
      payload: params
    });
  };

  handleSearch = e => {
    const { dispatch } = this.props;
    const { startTime, endTime } = this.state;
    const values = {
      ...e
    };
    this.setState({
      formValues: values
    });
    if (e == null) {
      values.currentPage = this.state.currentPage;
      values.pageSize = this.state.pageSize;
    } else {
      values.currentPage = 1;
      values.pageSize = 10;
    }
    values.rangeTime = undefined;
    values.startTime = startTime;
    values.endTime = endTime;
    dispatch({
      type: 'routeList/fetch',
      payload: values
    });
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.setState({
      formValues: {},
      currentPage: 1,
      pageSize: 10
    });
    dispatch({
      type: 'routeList/fetch'
    });
  };

  handleModalVisible = (flag, value) =>{
    if (!!flag){
      const { dispatch } = this.props;
      dispatch({
        type: 'routeList/fetchAll'
      }).then(res => {
        this.setState({ routes: res });
      })
    }else {
      this.setState({ iconVal: null });
    }
    this.setState({
      modalVisible: !!flag,
      updateFormValues: value || null
    });
  }

  handleUpdate = () => {
    if (!hasPermission('admin:update')){
      nopermission();
      return;
    }
    let values = this.formRef2.current.getFieldsValue();
    values.hideInMenu = (values.hideInMenu || values.hideInMenu == undefined) ? 1 : 0;
    values.roleId = values.access == 'canAdmin' ? '1,3' : '1,2,3';
    values.parentId = values.parentId == null ? 0 : values.parentId;
    if (values.id){
      update({...values}).then(res => {
        if (res.status == 200){
          message.success('修改成功!');
          this.handleModalVisible();
          this.handleSearch();
        }
      })
    }else {
      add({...values}).then(res => {
        if (res.status == 200){
          message.success('添加成功！');
          this.handleModalVisible();
          this.handleSearch();
        }
      })
    }
  }

  deleteRecord = id => {
    if (!hasPermission('admin:delete')){
      nopermission();
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'routeList/deleteById',
      payload: {
        id: id
      }
    }).then(res => {
      if (res.status == 200){
        message.success('删除成功！');
      }
      this.handleSearch();
    })
  };

  handleIconChg = e => {
    this.setState({
      iconVal: e.target.value
    })
  };

  renderSimpleForm() {

    return (
      <Form ref={this.formRef} onFinish={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.routeList.name' })} name='name'>
              <Input />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.routeList.parentId' })} name='parentName'>
              <Input />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.routeList.access' })} name='access'>
              <Radio.Group>
                <Radio value='canAdmin'>管理员</Radio>
                <Radio value='canUser'>普通用户</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={23}>
            <span className={styles.submitButtons} style={{ textAlign: 'left' }}>
              <Button type='primary' onClick={() => this.handleModalVisible(true,null)}>
                {formatMessage({ id: 'app.common.add' })}
              </Button>
              <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>
                <Icon type='search'/>{formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type='primary'
              >
                <Icon type='reload'/>{formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  renderModalContent = values => {
    const { routes, iconVal } = this.state;
    return (
      <Form ref={this.formRef2}>
        <Row>
          <Col span={11}>
            <Form.Item initialValue={values ? values.name : ''} label={formatMessage({ id: 'app.routeList.name' })} name='name'>
              <Input/>
            </Form.Item>
          </Col>
          <Col span={11} offset={1}>
            <Form.Item initialValue={values ? values.parentId : null} label={formatMessage({ id: 'app.routeList.parentId' })} name='parentId'>
              <Select>
                <Option value={0}>无</Option>
                {routes && routes.length > 0 && routes.map((item) => <Option value={item.id}>
                  <span className='.anticon.font'>
                    <span className={`iconfont ${item.icon}`}></span>
                    &nbsp;&nbsp;{item.name}
                  </span>
                </Option>)}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item initialValue={values ? values.icon : ''} label={formatMessage({ id: 'app.routeList.icon' })} name='icon'>
              <Input
                prefix={
                  <span className='.anticon.font'>
                    <span className={`iconfont ${!iconVal ? (values ? values.icon : '') : iconVal}`}></span>
                  </span>
                }
                onChange={this.handleIconChg}
              />
            </Form.Item>
          </Col>
          <Col span={11} offset={1}>
            <Form.Item initialValue={values ? values.path : ''} label={formatMessage({ id: 'app.routeList.path' })} name='path'>
              <Input/>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item initialValue={values ? values.component : ''} label={formatMessage({ id: 'app.routeList.component' })} name='component'>
              <Input/>
            </Form.Item>
          </Col>
          <Col span={11} offset={1}>
            <Form.Item initialValue={values ? values.access : ''} label={formatMessage({ id: 'app.routeList.access' })} name='access'>
              <Radio.Group>
                <Radio.Button value="canAdmin">管理员</Radio.Button>
                <Radio.Button value="canUser">普通用户</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11} offset={1}>
            <Form.Item label={formatMessage({ id: 'app.routeList.hideInMenu' })} name='hideInMenu'>
              <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked={values ? !values.hideInMenu : true}/>
            </Form.Item>
          </Col>
          <Col span={11} offset={1}>
            <Form.Item initialValue={values ? values.seq : ''} label={formatMessage({ id: 'app.routeList.seq' })} name='seq'>
              <InputNumber style={{ width: '90%'}}/>
            </Form.Item>
          </Col>
        </Row>
        {values &&
        <Row style={{ display: 'none'}}>
          <Col span={24}>
            <Form.Item initialValue={values.id} name='id'>
              <Input hidden={true}/>
            </Form.Item>
          </Col>
        </Row>}
      </Form>
    )
  }

  render() {
    const {
      routeList: {data},
      loading
    } = this.props;

    const { modalVisible, updateFormValues } = this.state;

    return (
      <>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <ProTable
            bordered={true}
            search={false}
            rowKey={record => record.id}
            loading={loading}
            dataSource={data ? data.list : []}
            pagination={data ? data.pagination : {}}
            columns={this.columns}
            onChange={this.handleBasicTableChange}
            size={"small"}
            options={{
              density: true,
              reload: () => {
                this.handleSearch();
              },
              fullScreen: true,
              setting: true
            }}
          />
        </div>
      </Card>
      {modalVisible &&
      <Modal
        destroyOnClose
        width={650}
        bodyStyle={{ paddingBottom: 0, paddingTop: 20 }}
        title={updateFormValues ? formatMessage({ id: 'app.routeList.update' }) : formatMessage({ id: 'app.routeList.add' })}
        visible={modalVisible}
        onOk={this.handleUpdate}
        onCancel={() => this.handleModalVisible(false, null)}
        afterClose={() => this.handleModalVisible()}
      >
        {this.renderModalContent(updateFormValues)}
      </Modal>
      }
      </>
    )
  }
}

export default connect(({ routeList, loading }) => ({
  routeList,
  loading: loading.effects['routeList/fetch']
}))(RouteList);
